package com.sig.agent;

/**
 * 热更管理
 *
 * @author sig
 * @since 2019/3/6
 */
public class HotUpdateService {
    private static HotUpdateService hotUpdateService = new HotUpdateService();
    private HotUpdateTask hotUpdateTask;

    public HotUpdateService() {
    }

    public static HotUpdateService getInstance() {
        return hotUpdateService;
    }

    public HotUpdateService(final String agentJar, final String reloadPath, long period, long keepTime) {
        this.startup(agentJar, reloadPath, period, keepTime);
    }

    /**
     * @param agentJar   @Value("${app.hotupdate.javaagent:./lib/sig-agent-1.0.1.RELEASE.jar}")
     * @param reloadPath @Value("{app.hotupdate.classes:./classes}")
     * @param period     @Value("app.hotupdate.period:5000")
     * @param keep       @Value("app.hotupdate.keep:30000")
     */
    public void startup(String agentJar, String reloadPath, long period, long keep) {
        boolean needDelete = hotUpdateTask == null;
        try {
            if (!running())
                hotUpdateTask = new HotUpdateTask(agentJar, reloadPath, period, keep, needDelete);
            hotUpdateTask.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean running() {
        return hotUpdateTask != null && hotUpdateTask.running();
    }

    public void destroy() {
        if (hotUpdateTask != null)
            hotUpdateTask.destroy();
    }

    public void shutdown() {
        if (running())
            hotUpdateTask.shutdown();
    }

    public HotUpdateTask hotUpdateTask() {
        return hotUpdateTask;
    }
}
